//
//  ST_UserManager.m
//  ST_BaseMall
//
//  Created by 昱胜 on 2022/9/2.
//

static NSString *kST_User = @"ST_User";
static NSString *kUserPath = @"kUserPath";
static NSString *kST_RCUser = @"ST_RCUser";
static NSString *kRCUserPath = @"kRCUserPath";
static NSString *KSaveAccessToken = @"ST_SaveAccessToken";
static NSString *KSaveRefreshToken = @"ST_SaveRefreshToken";
static NSString *KSaveOtherToken = @"ST_SaveOtherToken";

#import "ST_UserManager.h"
#import "HNSH_LoginHomeViewController.h"

@interface ST_UserManager ()

@property (strong, nonatomic) ST_UserInfo *user;
@property (strong, nonatomic) ST_UserRCModel *rcUser;

@end

@implementation ST_UserManager

+ (instancetype)shareInstance {
    static ST_UserManager *_shareInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!_shareInstance) {
            _shareInstance = [[[self class] alloc]init];
        }
    });
    return _shareInstance;
}

//是否登录
+ (BOOL)alreadyLogin {
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    // 从本地（@"weather" 文件中）获取.
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:kUserPath];
//    NSString *file1 = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:kRCUserPath];
    return [defaultManager fileExistsAtPath:file];
}

//更新个人信息
+ (void)uploadUserModelWithKey:(NSString *)key Value:(NSString *)Value {
    ST_UserInfo *user = [ST_UserManager shareInstance].user;
    [user setValue:Value forKey:key];
    [ST_UserManager saveUserModel:user];
}

- (void)saveAccountInfoWithAccessToken:(NSString *)accessToken RefreshToken:(NSString *)refreshToken {
    self.access_token = accessToken;
    self.refresh_token = refreshToken;
    if (accessToken) {
        [[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:KSaveAccessToken];
        [[NSUserDefaults standardUserDefaults]setObject:refreshToken forKey:KSaveRefreshToken];
        [[NSUserDefaults standardUserDefaults] synchronize];
    } else {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:KSaveAccessToken];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:KSaveRefreshToken];
    }
}

- (void)saveOtherTokenWithOtherToken:(NSString *)otherToken {
    self.other_token = otherToken;
    if (otherToken) {
        [[NSUserDefaults standardUserDefaults]setObject:otherToken forKey:KSaveOtherToken];
        [[NSUserDefaults standardUserDefaults] synchronize];
    } else {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:KSaveOtherToken];
    }
}


/**
 *  写入当前用户
 */
+ (BOOL)saveUserModel:(ST_UserInfo *)user {
    [ST_UserManager shareInstance].user = user;
    // 创建归档时所需的data 对象.
    NSMutableData *data = [NSMutableData data];
    // 归档类.
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    // 开始归档（@"model" 是key值，也就是通过这个标识来找到写入的对象）.
    [archiver encodeObject:user forKey:kST_User];
    // 归档结束.
    [archiver finishEncoding];
    // 写入本地（@"weather" 是写入的文件名）.
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:kUserPath];
    return [data writeToFile:file atomically:YES];
}

/**
 *  写入当前融云用户
 */
+ (BOOL)saveRCUserModel:(ST_UserRCModel *)rcUser {
    [ST_UserManager shareInstance].rcUser = rcUser;
    // 创建归档时所需的data 对象.
    NSMutableData *data = [NSMutableData data];
    // 归档类.
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    // 开始归档（@"model" 是key值，也就是通过这个标识来找到写入的对象）.
    [archiver encodeObject:rcUser forKey:kST_RCUser];
    // 归档结束.
    [archiver finishEncoding];
    // 写入本地（@"weather" 是写入的文件名）.
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:kRCUserPath];
    return [data writeToFile:file atomically:YES];
}

//登录
+ (void)gotoLogin {
    [ST_UserManager logOut];
//    HNSH_LoginHomeViewController *vc = [[HNSH_LoginHomeViewController alloc]init];
//    ST_BaseNavigationController *nav = [[ST_BaseNavigationController alloc]initWithRootViewController:vc];
//    nav.modalPresentationStyle = UIModalPresentationFullScreen;
//    [[UIViewControllerHelper findCurrentShowingViewController] presentViewController:nav animated:YES completion:nil];
}

//退出登录
+ (void)logOut {
    //删除本地个人信息
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    // 从本地（@"weather" 文件中）获取.
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:kUserPath];
    if([defaultManager isDeletableFileAtPath:file]) {
        [defaultManager removeItemAtPath:file error:nil];
    }
    
    //删除本地融云信息
    NSString *rcFile = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:kRCUserPath];
    if([defaultManager isDeletableFileAtPath:rcFile]) {
        [defaultManager removeItemAtPath:rcFile error:nil];
    }
    
    [HNSH_RYTools disconnect];
    //删除token信息
    [[ST_UserManager shareInstance] saveAccountInfoWithAccessToken:@"" RefreshToken:@""];
    
    HNSH_LoginHomeViewController *vc = [[HNSH_LoginHomeViewController alloc]init];
    ST_BaseNavigationController *nav = [[ST_BaseNavigationController alloc]initWithRootViewController:vc];
    kSTWindow.rootViewController = nav;
}


//请求个人信息
- (void)loadUserInfoComplate:(void(^)(void))complate {
    [HNSH_UserNetServer requestUserDetailSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [ST_UserManager saveUserModel:[ST_UserInfo yy_modelWithDictionary:responseObject.resultset]];
            if (complate) {
                complate();
            }
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//请求融云信息
- (void)loadRcUserInfoComplate:(void(^)(void))complate {
    [HNSH_UserNetServer requestRcUserDetailSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [ST_UserManager saveRCUserModel:[ST_UserRCModel yy_modelWithDictionary:responseObject.resultset]];
            if (complate) {
                complate();
            }
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//请求三方网页登录信息
- (void)loadOtherTokenComplate:(void(^)(void))complate {
    [HNSH_UserNetServer requestBingBirdUnionLoginSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [[ST_UserManager shareInstance] saveOtherTokenWithOtherToken:responseObject.resultset[@"token"]];
            if (complate) {
                complate();
            }
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}


#define mark lazy
- (ST_UserInfo *)user {
    if (!_user) {
        // 从本地（@"weather" 文件中）获取.
        NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:kUserPath];
        // data.
        NSData *data = [NSData dataWithContentsOfFile:file];
        // 反归档.
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        // 获取@"model" 所对应的数据
        _user = [unarchiver decodeObjectForKey:kST_User];
        // 反归档结束.
        [unarchiver finishDecoding];
    }
    return _user;
}

- (ST_UserRCModel *)rcUser {
    if (!_rcUser) {
        // 从本地（@"weather" 文件中）获取.
        NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:kRCUserPath];
        // data.
        NSData *data = [NSData dataWithContentsOfFile:file];
        // 反归档.
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        // 获取@"model" 所对应的数据
        _rcUser = [unarchiver decodeObjectForKey:kST_RCUser];
        // 反归档结束.
        [unarchiver finishDecoding];
    }
    return _rcUser;
}

- (NSString *)access_token {
    if (!_access_token) {
        if ([[NSUserDefaults standardUserDefaults] valueForKey:KSaveAccessToken]) {
            _access_token = [[NSUserDefaults standardUserDefaults] valueForKey:KSaveAccessToken];
        } else {
            _access_token = @"";
        }
    }
    return _access_token;
}

- (NSString *)refresh_token {
    if (!_refresh_token) {
        if ([[NSUserDefaults standardUserDefaults] valueForKey:KSaveRefreshToken]) {
            _refresh_token = [[NSUserDefaults standardUserDefaults] valueForKey:KSaveRefreshToken];
        } else {
            _refresh_token = @"";
        }
    }
    return _refresh_token;
}

- (NSString *)other_token {
    if (!_other_token) {
        if ([[NSUserDefaults standardUserDefaults] valueForKey:KSaveOtherToken]) {
            _other_token = [[NSUserDefaults standardUserDefaults] valueForKey:KSaveOtherToken];
        } else {
            _other_token = @"";
        }
    }
    return _other_token;
}

@end
